#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include <unistd.h>

#include "Log.hpp"
#include "Com_ERR.hpp"
#include "Inet_Addr.hpp"

namespace SocketModule
{
    using namespace LogModule;

    class Socket;
    using SockSPtr = std::shared_ptr<Socket>;

    const static int g_backlog = 8; // 默认全连接队列的长度 是 8

    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void CreateBindOrDie(uint16_t port) = 0;
        virtual void CreateListenOrDie(int backlog = g_backlog) = 0;
        virtual SockSPtr Accepter(Inet_Addr* clientAddr) = 0;
        virtual bool Connnector(std::string &server_ip, uint16_t port) = 0;

        virtual int Sockfd() = 0;
        virtual void Close() = 0;

        virtual  ssize_t Recv(std::string* out) = 0;
        virtual ssize_t Send(std::string& in) = 0;

    public:
        void BuildListenSocket(uint16_t port)
        {
            CreateSocketOrDie();
            CreateBindOrDie(port);
            CreateListenOrDie();
        }

        bool BuildClientSocket(std::string &server_ip, uint16_t port)
        {
            CreateSocketOrDie();
            return Connnector(server_ip, port);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket() {}

        TcpSocket(int sockfd)
            : _sockfd(sockfd)
        {
        }

        ~TcpSocket() {}

        void CreateSocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket create failed!\n");
                exit(SOCKET_ERROR);
            }
            LOG(DEBUG, "socket create success, sockfd is %d\n", _sockfd);
        }

        void CreateBindOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;         // IpV4
            local.sin_port = htons(port);       // 将主机序列转为网络序列
            local.sin_addr.s_addr = INADDR_ANY; // 服务端的 ip 设置为 任意

            if (::bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                LOG(FATAL, "bind failed\n");
                exit(BIND_ERROR);
            }
            LOG(DEBUG, "bind success!\n");
        }

        void CreateListenOrDie(int backlog) override
        {
            if (::listen(_sockfd, backlog) < 0)
            {
                LOG(FATAL, "listen failed\n");
                exit(LISTEN_ERROR);
            }
            LOG(DEBUG, "listen success\n");
        }

        SockSPtr Accepter(Inet_Addr* clientAddr) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int newsock = ::accept(_sockfd, (struct sockaddr *)&client, &len);
            if (newsock < 0)
            {
                LOG(FATAL, "accept failed!\n");
                return nullptr;
            }
            *clientAddr = client;// 默认的拷贝构造
            return std::make_shared<TcpSocket>(newsock);
        }

        bool Connnector(std::string &server_ip, uint16_t port) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;                             // IpV4
            server.sin_port = htons(port);                           // 将端口转为 网络序列
            inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr); // 将地址转为网络序列

            if(::connect(_sockfd, (struct sockaddr*)&server, sizeof(server)) < 0)
            {
                LOG(FATAL, "client connect failed\n");
                return false;
            }
            LOG(FATAL, "client connect success\n");
            return true;
        }

        int Sockfd() override
        {
            return _sockfd;
        }

        void Close() override
        {
            if(_sockfd > 0)
                ::close(_sockfd);
        }

        ssize_t Recv(std::string* out) override
        {
            char buffer[4096];
            ssize_t n = ::recv(_sockfd, buffer, sizeof(buffer)-1, 0);
            if(n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }
            return n;
        }

        ssize_t Send(std::string& in) override
        {
            return ::send(_sockfd, in.c_str(),in.size(), 0);
        }

    private:
        int _sockfd; // 可以是 listen 套接字 也可以是 IO 套接字
    };

} // namespace SocketModule
